package com.skt.casdemo.view;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;


import com.skt.casdemo.R;

import android.media.AudioManager;
import android.net.Uri;

import android.os.Bundle;
import android.os.Handler;

import android.provider.CallLog;
import android.app.Activity;
import android.app.AlertDialog;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.PopupWindow;

import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemClickListener, OnInitListener {
	
	private ListView listview;
	private ArrayList<String> menu;
	private ArrayList<String> list;
	
	private TextToSpeech tts;
	
	protected static final int RESULT_VIEW_LIST = 0;
	protected static final int RESULT_SPEECH = 1;
	
	private static final long DOUBLE_PRESS_INTERVAL = 500;
	private long lastPressTime = 0;
	
	static final String mURLClientLogin = "https://www.google.com/accounts/ClientLogin";
	static String mAuthTokenCal;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        tts = new TextToSpeech(this, this);
        tts.setLanguage(Locale.KOREAN);
        
        menu = new ArrayList<String>();
        menu.add("Google Speech I/O Test");
        menu.add("View installed Application list");
        menu.add("View call log list");
        menu.add("Launch another App");
        menu.add("Phone Call");
        menu.add("View Google Calendar");
        menu.add("Resolution Test1");
        menu.add("Resolution Test2(width)");
        menu.add("Resolution Test3(height)");
        menu.add("WebView Test");
        menu.add("Popup Window");
        menu.add("TTS Speaker Test");
        
        list = new ArrayList<String>();
        
        listview = (ListView)findViewById(R.id.listView1);
        listview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, menu));
        listview.setOnItemClickListener(this);
        
        Resources resources = getResources();
        String dpi = Integer.toString(resources.getDisplayMetrics().densityDpi);
        Log.d("Context Aware", dpi);
        //Log.d("Context Aware", "");

    }
    
    public void onInit(int status) {
		// TODO Auto-generated method stub
	}
    
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		switch (requestCode) {
		case RESULT_VIEW_LIST:
			break;

		case RESULT_SPEECH:
			if (resultCode == RESULT_OK && null != data) {
				ArrayList<String> text = data
						.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
				Toast.makeText(getApplicationContext(),text.get(0),Toast.LENGTH_LONG).show();
				
//				HashMap<String, String> hm = new HashMap<String, String>();
//				hm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_VOICE_CALL));
//				tts.speak("수화음 음성 테스트입니다.", TextToSpeech.QUEUE_FLUSH, hm);
//				AudioManager am = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
//				am.setStreamMute(AudioManager.STREAM_VOICE_CALL, true);
				
				tts.speak(text.get(0), TextToSpeech.QUEUE_FLUSH, null);
				
				if(text.get(0).equals("스마트청구서")){
					Intent intent = getPackageManager().getLaunchIntentForPackage("com.skt.smartbill");
					startActivity(intent);
				}
			}
			break;
		
		default :
			break;
		}
	}
	
	@Override
	protected void onDestroy() {
		if (tts != null){
			tts.stop();
			tts.shutdown();
		}
		
		super.onDestroy();
	}

	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		String str = (String)parent.getItemAtPosition(position);
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
        
		switch (position){
				
		case 0: Log.d("Context Aware", "Google Speech I/O Test");
				speechInOut();
				break;
				
		case 1: Log.d("Context Aware", "View installed Application list");
				viewInstalledApp();
				break;
		
		case 2: Log.d("Context Aware", "View call log list");
				viewCallLog();
				break;
				
		case 3: Log.d("Context Aware", "Launch another App");
				launchApp();
				break;
				
		case 4: Log.d("Context Aware", "Fake Call");
				fakeCall();
				break;
				
		case 5: Log.d("Context Aware", "View Google Calendar");
				viewGoogleCalendar();
				break;
				
		case 6: Log.d("Context Aware", "Resolution Test 1");
				viewResolutionTest(1);
				break;
				
		case 7: Log.d("Context Aware", "Resolution Test2(width)");
				viewResolutionTest(2);
				break;
		
		case 8: Log.d("Context Aware", "Resolution Test3(height)");
				viewResolutionTest(3);
				break;
		
		case 9: Log.d("Context Aware", "Webview Test");
				viewWebview();
				
		case 10: Log.d("Context Aware", "Popup Window Test");
				viewPopup();
				
		case 11: Log.d("Context Aware", "TTS Speaker Test");
				ttsSpeakerTest();
				
		default : Log.d("Context Aware", "none"); 
				break;
		}
	}
	
	private void speechInOut(){
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");

		try {
			startActivityForResult(intent, RESULT_SPEECH);
		} catch (ActivityNotFoundException a) {
			Toast.makeText(getApplicationContext(),"Device doesn't support Speech Input/Output",Toast.LENGTH_SHORT).show();
		}
	}//speechInOut
	
	private void viewInstalledApp(){
		List<ApplicationInfo> packages = getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
		list.clear();
		
		for (ApplicationInfo packageInfo : packages){
			list.add(packageInfo.packageName);
			//Log.d("Context Aware", "Installed package : " + packageInfo.packageName);
			//Log.d("Context Aware", "Launch Activity : " + pm.getLaunchIntentForPackage(packageInfo.packageName));
		}
		
		viewList(list);
	}// viewInstalledApp
	
	private void viewCallLog(){
		String[] projection = {
			CallLog.Calls.TYPE, 
			CallLog.Calls.NUMBER, 
			CallLog.Calls.DATE, 
			CallLog.Calls.DURATION 
		};
		
		String selection = null;
		String[] selectionArg = null;
		String sortOrder = CallLog.Calls.DEFAULT_SORT_ORDER;	
		
		Cursor cur = this.getContentResolver().query(CallLog.Calls.CONTENT_URI, 
													 projection, 
													 selection, 
													 selectionArg, 
													 sortOrder);
		
		Log.d("db count=", String.valueOf(cur.getCount()));
		
		list.clear();
		
		if(cur.moveToFirst() && cur.getCount() > 0) {
			   while(cur.isAfterLast() == false) {
				   StringBuffer sb = new StringBuffer();
				   sb.append("call type=").append(cur.getString(cur.getColumnIndex(CallLog.Calls.TYPE)));
			       sb.append(", content number=").append(cur.getString(cur.getColumnIndex(CallLog.Calls.NUMBER)));
			       sb.append(", date=").append(timeToString(cur.getLong(cur.getColumnIndex(CallLog.Calls.DATE))));
			       sb.append(", duration=").append(cur.getString(cur.getColumnIndex(CallLog.Calls.DURATION))).append("]");
			       cur.moveToNext();
			       
			       //Log.d("call history[", sb.toString());
			       list.add("call history[" + sb.toString());
			   }
		}
		viewList(list);
	} //viewCallLog
	
	private void launchApp(){
		Intent intent = getPackageManager().getLaunchIntentForPackage("com.skt.smartbill");
		startActivity(intent);
	}//launchApp
	
	// http://code.google.com/p/cs-4220-metawatch/source/browse/trunk/MetaWatch/res/layout/fakecall.xml?r=8
	private void fakeCall(){
		Intent intent = new Intent(this, FakeCallActivity.class);
		startActivity(intent);
	}//fakeCall
	
	private void viewGoogleCalendar(){
		String[] projection = new String[]{
				"_id",
				"calendar_id",
				"title",
				"eventLocation",
				"eventStatus",
				"description",
				"dtstart",
				"dtend",
				//"allDay",
				//"deleted"
		};
		
//		Calendar start_dt = Calendar.getInstance();
//		start_dt.add(Calendar.DATE, -1);
//		Calendar end_dt = Calendar.getInstance();
//		end_dt.add(Calendar.DATE, 1);
		
		String start_dt = "201211120000";
		String end_dt = "201211140000";
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddkkmm");
		Calendar calendar = Calendar.getInstance();
		Date startDate = new Date();
		Date endDate = new Date();
		try{
			startDate = format.parse(start_dt);
			endDate = format.parse(end_dt);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		Log.d("View Google Calendar", start_dt + " : " + start_dt.toString());
		Log.d("View Google Calendar", end_dt + " : " + end_dt.toString());
		
		Uri uri = Uri.parse("content://com.android.calendar/events");
		String selection = "deleted=0 AND (dtstart between "+startDate.getTime()+" AND "+endDate.getTime()+" )";
		String[] selectionArg = null;
		String sortOrder = "dtstart asc";		
		
		Cursor cur = getApplicationContext().getContentResolver().query(uri, 
																			projection, 
																			selection,
																			null ,
																			sortOrder);
		
		list.clear();
		
		if(cur == null || !cur.moveToFirst()){
			Log.d("View Google Calendar", "Google calendar does not exist!");
			return;
		}
		
		Log.d("View Google Calendar", "검색결과 : " + String.valueOf(cur.getCount()));
		
		if(cur.moveToFirst() && cur.getCount() > 0) {
			   while(cur.isAfterLast() == false) {
				   StringBuffer sb = new StringBuffer();
				   sb.append("ID=").append(cur.getString(cur.getColumnIndex("_id")));
				   sb.append("Calendar ID=").append(cur.getString(cur.getColumnIndex("calendar_id")));
			       sb.append(", Title=").append(cur.getString(cur.getColumnIndex("title")));
			       //sb.append(", Description=").append(getString(cur.getColumnIndex("description")));
			       sb.append(", Location=").append(cur.getString(cur.getColumnIndex("eventLocation")));
			       sb.append(", Status=").append(String.valueOf(cur.getInt(cur.getColumnIndex("eventStatus"))));
			       sb.append(", Start_Dt=").append(timeToString(cur.getLong(cur.getColumnIndex("dtstart"))));
			       sb.append(", End_Dt=").append(timeToString(cur.getLong(cur.getColumnIndex("dtend")))).append("]");
			       cur.moveToNext();
			       
			       //Log.d("call history[", sb.toString());
			       list.add("Calendar [" + sb.toString());
			   }
		}
		viewList(list);
	}//viewGoogleCalendar
	
	private void viewResolutionTest(int type){
		Intent intent = new Intent(this, ScreenTestActivity.class);
		intent.putExtra("type", type);
		startActivity(intent);
	}//viewResolutionTest
	
	private void viewWebview(){
		Intent intent = new Intent(this, WebViewActivity.class);
		startActivity(intent);
	}//viewWebview
	
	private String timeToString(Long time) {
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleFormat.format(new Date(time));
        return date;
    }//timeToString
	
	private void viewList(ArrayList<String> list){
		Intent intent = new Intent(this, ListViewActivity.class);
		intent.putStringArrayListExtra("list", list);
		startActivityForResult(intent, RESULT_VIEW_LIST);
	}//viewList
	
	private void viewPopup(){
		LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
		
		View popupView = layoutInflater.inflate(R.layout.popup, null);
		
		final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		
		popupWindow.showAsDropDown(listview);
	}//viewPopup
	
	private void ttsSpeakerTest(){
		Intent intent = new Intent(this, null);
		startActivity(intent);
	}//ttsSpeakerTest

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if (keyCode == KeyEvent.KEYCODE_BACK){
			long pressTime = System.currentTimeMillis();
			
			if (pressTime - lastPressTime <= DOUBLE_PRESS_INTERVAL){
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder
				.setMessage("어플리케이션을 종료하시겠습니까?")
				.setCancelable(false)
				.setPositiveButton("예", new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Toast.makeText(getApplicationContext(), "yes", Toast.LENGTH_LONG).show();
						MainActivity.this.finish();
					}
				})
				.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_LONG).show();
					}
				});
				builder.create().show();
				
			}
			
			lastPressTime = pressTime;
		}
	
		return false;
	}
}
